package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;
    //每分钟执行一次,对超时未支付的订单自动取消
    @Scheduled(cron = "0 * * * * ? ")
    public void CancelTimeoutOrder() {
        log.info("检查是否订单超时未支付:{}", new Date());
        LocalDateTime timeout = LocalDateTime.now().plusMinutes(-15);
        List<Orders> ordersList= orderMapper.getTimeout(Orders.PAID,timeout);
        //更改超时为支付的订单
        ordersList.forEach(order -> {
            order.setStatus(Orders.CANCELLED);
            order.setCancelReason("订单超时，自动取消");
            order.setCancelTime(LocalDateTime.now());
            orderMapper.update(order);
        });

    }
    //对一直处于在派送都订单，自动完成订单
    @Scheduled(cron = "0 0 1 * * ?")//每天凌晨1点执行
    public void CancelOrder() {
        log.info("检查是否有订单长时间在派送中:{}", new Date());
        LocalDateTime timeout = LocalDateTime.now().plusMinutes(-60);
        //查询需要改变派送中状态的订单
        List<Orders> ordersList = orderMapper.getTimeout(Orders.DELIVERY_IN_PROGRESS, timeout);
        //更新订单状态为完成
        ordersList.forEach(order -> {
            order.setStatus(Orders.COMPLETED);
            order.setDeliveryTime(LocalDateTime.now());
            orderMapper.update(order);
        });
    }
    //对一直处于待接单的订单，自动取消订单
    @Scheduled(cron = "0 0 1 * * ?")//每天凌晨1点执行
    public void CancelOrder1() {
        log.info("检查是否有订单长时间在待接单中:{}", new Date());
        LocalDateTime timeout = LocalDateTime.now().plusMinutes(-60);
        //查询需要改变派送中状态的订单
        List<Orders> ordersList = orderMapper.getTimeout(Orders.TO_BE_CONFIRMED, timeout);
        //更新订单状态为完成
        ordersList.forEach(order -> {
            order.setStatus(Orders.CANCELLED);
            order.setCancelReason("订单长时间未接单，自动取消");
            order.setCancelTime(LocalDateTime.now());
            orderMapper.update(order);
        });
    }
}
